package com.gitee.fanx.retty.spring;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

import com.gitee.fanx.retty.web.Request;
import com.gitee.fanx.retty.web.Route;

/**
 * @author fanhang
 */
public class MethodRoute implements Route {

	private final Object bean;
	private final Method method;
	private final List<ParamResolver> paramResolvers;

	public MethodRoute(Object bean, Method method, List<ParamResolver> paramResolvers) {
		this.bean = bean;
		this.method = method;
		this.paramResolvers = paramResolvers;
	}

	@Override
	public Object handle(Request request) throws Throwable {
		if (this.paramResolvers.isEmpty()) {
			return method.invoke(bean);
		}
		List<Object> args = this.paramResolvers.stream().map(i -> i.resolve(request)).collect(Collectors.toList());
		try {
			return method.invoke(bean, args.toArray());
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}

	public Object getBean() {
		return bean;
	}

	public Method getMethod() {
		return method;
	}

	@Override
	public String toString() {
		return String.format("MethodRoute{%s#%s(%s)}", bean.getClass().getSimpleName(), method.getName(),
				paramResolvers.stream().map(i -> i.toString()).collect(Collectors.joining(",")));
	}

}
